package com.yunhe.abnormal.repository.data;

import com.yunhe.abnormal.domain.data.AbnormalEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AbnormalEventRepository extends JpaRepository<AbnormalEvent, Long> {
    /**
     * 查询全部异常事件列表
     *
     * @param spec     查询条件
     * @param pageable 分页对象
     */
    Page<AbnormalEvent> findAll(Specification<AbnormalEvent> spec, Pageable pageable);

    /**
     * 查询全部异常事件记录
     *
     * @param spec 查询条件
     * @param sort 排序对象
     */
    Iterable<AbnormalEvent> findAll(Specification<AbnormalEvent> spec, Sort sort);

    /**
     * 查询全部异常事件记录
     *
     * @param spec 查询条件
     */
    Iterable<AbnormalEvent> findAll(Specification<AbnormalEvent> spec);

    @Query(value = "select * from data_abnormal_event where abnormal_rule_id=:ruleId and alarm_level_id=:levelId and abnormal_status_id!=:statusId",
            nativeQuery= true)
    List<AbnormalEvent> findByRuleIdAndLevelIdAndStatusId(@Param("ruleId") Long ruleId, @Param("levelId") Long levelId, @Param("statusId") Long statusId);

    @Query(value = "select * from data_abnormal_event where abnormal_rule_id=:ruleId and abnormal_status_id!=:statusId", nativeQuery= true)
    List<AbnormalEvent> findByRuleIdAndStatusId(@Param("ruleId") Long ruleId, @Param("statusId") Long statusId);

    @Query(value = "select * from data_abnormal_event where abnormal_rule_id=:ruleId and process_rtime>=:startRtime and process_rtime<=:endRtime order by " +
            "start_rtime desc limit 1", nativeQuery= true)
    AbnormalEvent findFirstEventByRuleAndTimeRange(@Param("ruleId") Long ruleId, @Param("startRtime") Long startRtime, @Param("endRtime") Long endRtime);

    @Query(value = "select * from data_abnormal_event where abnormal_rule_id=:ruleId and start_rtime<=:startRtime  and (process_rtime is null or " +
            "process_rtime>=:endRtime) order by start_rtime desc limit 1", nativeQuery= true)
    AbnormalEvent getLastHistoryEventByStartTime(@Param("ruleId") Long ruleId, @Param("startRtime") Long startRtime, @Param("endRtime") Long endRtime);

    @Query(value = "select * from data_abnormal_event where abnormal_rule_id=:ruleId and start_rtime=:startRtime limit 1", nativeQuery= true)
    AbnormalEvent findSameRuleAndRtime(@Param("ruleId") Long ruleId, @Param("startRtime") Long startRtime);

    @Query(value = "select * from data_abnormal_event where abnormal_status_id=:statusId", nativeQuery= true)
    List<AbnormalEvent> findAllReadyEvents(@Param("statusId") Long statusId);
}
